import 'dart:async';

import 'package:chathouse/pages/client/account/email_notice_setting.dart';
import 'package:chathouse/pages/client/account/update_pwd.dart';
import 'package:chathouse/pages/client/account/use_clause_page.dart';
import 'package:chathouse/pages/route_manager/root_route_manager.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/log.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../constant/app_constant.dart';
import '../../../model/member_info.dart';
import '../../../model/response_bean.dart';
import '../../../public/event_bus.dart';
import '../../../push/chat_house_push.dart';
import '../../../util/base_utils.dart';
import '../../guide/about_page.dart';
import '../../login/login_page.dart';
import '../../login/select_role_page.dart';
import 'account_privacy_page.dart';
import 'contact_us.dart';
import 'edit_account_page.dart';

class ClientAccountPage extends StatefulWidget {
  const ClientAccountPage({Key? key}) : super(key: key);

  @override
  State<ClientAccountPage> createState() => _ClientAccountPageState();
}

class _ClientAccountPageState extends State<ClientAccountPage>
    with AutomaticKeepAliveClientMixin, NavigationHelper {
  MemberInfo? _memberInfo;
  static var textStyle =
      getTextStyle(24.sp, fontType: FontType.BOLD, color: Colors.black);

  @override
  bool get wantKeepAlive => true;
  StreamSubscription? refreshSubscription;

  @override
  void dispose() {
    refreshSubscription?.cancel();
    super.dispose();
  }

  var isShowTour = false;

  @override
  void initState() {
    super.initState();
    Obj.showLoading();
    getMembersInfo();

    refreshSubscription =
        eventBus.on<UpdateClientAccountEvent>().listen((event) {
      getMembersInfo();
    });

    Apis.isShowTourist().then((value) async {
      var result = ResponseBean.fromJson(value?.data ?? {});
      if (result.isRequestSuccess) {
        setState(() {
          isShowTour = true;
        });
      }
    }).catchError((error) {
      LogUtil.d("isShowTourist Error $error");
    });
  }

  getMembersInfo() {
    Apis.getMembersInfo().then((value) {
      Obj.dismissLoading();
      var jsonData = value?.data;
      _memberInfo = MemberInfo.fromJson(jsonData);
      SpUtil.putObject(AppConstant.memberInfo, _memberInfo!);
      LogUtil.d("getMembersInfo success ");
      setState(() {});
      Obj.dismissLoading();
    }).catchError((error) {
      Obj.dismissLoading();
      LogUtil.d("getMembersInfo error");
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        appBar: getAppBar(leading: Container()),
        body: SafeArea(
          child: ListView(
            children: [
              SizedBox(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Stack(
                      children: [
                        Text('歡迎回來',
                                style: getTextStyle(30.sp,
                                    fontType: FontType.BOLD,
                                    color: Colors.black))
                            .setContainer(
                                margin: EdgeInsets.only(left: Styles.magin_24)),
                        Text(_memberInfo?.data?.membersName ?? "",
                                style: getTextStyle(20.sp,
                                    fontType: FontType.BOLD,
                                    color: Colors.black))
                            .setContainer(
                                margin: EdgeInsets.only(
                                    left: Styles.magin_24, top: 50.w)),
                      ],
                    ),
                    Container(
                        child: (_memberInfo?.data?.memberImage.isNullOrEmpty ??
                                true)
                            ? ImageUtils.image(Res.expert_avatar,
                                    width: 80.w, height: 80.w, radius: 40.w)
                                .setContainer(
                                    margin:
                                        EdgeInsets.only(right: Styles.magin_24))
                            : ImageUtils.image(
                                    _memberInfo?.data?.memberImage ?? "",
                                    imageType: ImageType.NETWORK,
                                    width: 80.w,
                                    height: 80.w,
                                    radius: 40.w)
                                .setContainer(
                                    margin: EdgeInsets.only(
                                        right: Styles.magin_24)))
                  ],
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              ListView(
                itemExtent: 44.w,
                children: [
                  MyContainer(
                    child: Container(
                      alignment: Alignment.centerLeft,
                      child: InkWell(
                          onTap: () async {
                            navigateTo(const EditAccountPage(),
                                onResult: (result) {
                              LogUtil.d("result1 $result");
                              if (result == 100) {
                                LogUtil.d("result2 $result");
                                getMembersInfo();
                              }
                            });
                            // var result = await Get.to(const EditAccountPage());
                            // LogUtil.d("result1 $result");
                            // if (result == 100) {
                            //   LogUtil.d("result2 $result");
                            //   getMembersInfo();
                            // }
                          },
                          child:
                          // Text(
                          //   "> 編輯個人檔案",
                          //   style: textStyle,
                          // )
                          MyText(
                            textStyle: textStyle, str: "編輯檔案", iconData: Icons.person, color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                          )
                      ),
                    ),
                  ),
                  MyContainer(
                    child: Container(
                      alignment: Alignment.centerLeft,
                      child: InkWell(
                          onTap: () {
                            navigateTo(EmailNoticeSettingPage(1));
                          },
                          child:
                          // Text(
                          //   "> 電郵及通知設定",
                          //   style: textStyle,
                          // )
                          MyText(
                            textStyle: textStyle, str: "電郵及通知設定", iconData: Icons.notifications, color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                          )
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      MyContainer(
                        child: InkWell(
                            onTap: () {
                              Get.defaultDialog(
                                  title: "確定轉到專家版嗎？",
                                  textCancel: "取消",
                                  textConfirm: "確定",
                                  middleText: "",
                                  buttonColor: Colors.white,
                                  cancelTextColor: MyColors.black_0000011,
                                  confirmTextColor: MyColors.black_0000011,
                                  radius: 20.w,
                                  titlePadding: EdgeInsets.all(20.w),
                                  onConfirm: () {
                                    SpUtil.clear();
                                    //初始化極光
                                    ChatHousePush.instance.initPlatformState();
                                    Get.offAll(const SelectRolePage());
                                    SpUtil.putString(Keys.userRole, "b");
                                    AppConstant.userRole = UserRole.b;
                                    Get.to(LoginPage());
                                    //獲取token
                                    String token = SpUtil.getString(Keys.token);
                                    LogUtil.d("TOKEN: $token");
                                  },
                                  onCancel: () {
                                    Get.back();
                                  });
                            },
                            child:
                            // Text(
                            //   "> 轉到專家版",
                            //   style: textStyle,
                            // )
                            MyText(
                              textStyle: getTextStyle(24.sp, fontType: FontType.BOLD, color: Color(0xFFFEFBEA)), str: "轉到專家版", iconData: Icons.switch_account, color: Color(0xFFFEFBEA), bgColor: Color(0xFFF19C38),
                            )
                        ),
                      ),
                    ],
                  ),
                  MyContainer(
                    child: Container(
                      alignment: Alignment.centerLeft,
                      child: InkWell(
                          onTap: () => {Get.to(ContactUsPage(1))},
                          child:
                          // Text(
                          //   "> 聯絡我們",
                          //   style: textStyle,
                          // )
                          MyText(
                            textStyle: textStyle, str: "聯絡我們", iconData: Icons.headphones, color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                          )
                      ),
                    ),
                  ),
                  MyContainer(
                    child: Container(
                      alignment: Alignment.centerLeft,
                      child: InkWell(
                          onTap: () => {Get.to(UpdatePwdPage(1))},
                          child:
                          // Text(
                          //   "> 重設密碼",
                          //   style: textStyle,
                          // )
                          MyText(
                            textStyle: textStyle, str: "重設密碼", iconData: Icons.info_outline, color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                          )
                      ),
                    ),
                  ),
                  MyContainer(
                    child: Container(
                      alignment: Alignment.centerLeft,
                      child: InkWell(
                          onTap: () => {Get.to(const AboutPage())},
                          child:
                          // Text(
                          //   "> 屋測測簡介及教學",
                          //   style: textStyle,
                          // )
                          MyText(
                            textStyle: textStyle, str: "屋測測簡介及教學", iconData: Icons.tips_and_updates, color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                          )
                      ),
                    ),
                  ),
                  MyContainer(
                    child: Container(
                      alignment: Alignment.centerLeft,
                      child: InkWell(
                          onTap: () => Get.to(UseClausePage()),
                          child:
                          // Text(
                          //   "> 平台使用條款",
                          //   style: textStyle,
                          // )
                          MyTextNoIcon(
                            textStyle: textStyle, str: "平台使用條款", bgColor: Color(0xFFC5D6AC),
                          )
                      ),
                    ),
                  ),
                  MyContainer(
                    child: Container(
                      alignment: Alignment.centerLeft,
                      child: InkWell(
                          onTap: () => {Get.to(ClientPrivacyPage())},
                          child:
                          // Text(
                          //   "> 私隱政策聲明",
                          //   style: textStyle,
                          // )
                          MyTextNoIcon(
                            textStyle: textStyle, str: "隱私政策聲明", bgColor: Color(0xFFC5D6AC),
                          )
                      ),
                    ),
                  ),
                  Visibility(
                    visible: isShowTour,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      child: InkWell(
                          onTap: () => {
                                Get.defaultDialog(
                                    title: "確定註銷賬號嗎？",
                                    textCancel: "取消",
                                    textConfirm: "確定",
                                    middleText: "",
                                    buttonColor: Colors.white,
                                    cancelTextColor: MyColors.black_0000011,
                                    confirmTextColor: MyColors.black_0000011,
                                    radius: 20.w,
                                    titlePadding: EdgeInsets.all(20.w),
                                    onConfirm: () {
                                      SpUtil.clear();
                                      //初始化極光
                                      ChatHousePush.instance
                                          .initPlatformState();
                                      Get.offAll(const SelectRolePage());
                                      // SpUtil.putString(Keys.userRole, "b");
                                      // AppConstant.userRole = UserRole.b;
                                      // Get.to(LoginPage());
                                      // //獲取token
                                      // String token = SpUtil.getString(Keys.token);
                                      // LogUtil.d("TOKEN: $token");
                                      Apis.deleteMember({
                                        "membersIds": _memberInfo
                                            ?.data?.membersId
                                            .toString()
                                      })
                                          .then((value) => {
                                                ToastUtil.showToast("注销账号成功"),
                                              })
                                          .onError((error, stackTrace) => {
                                                ToastUtil.showToast("注销账号成功"),
                                              });
                                    },
                                    onCancel: () {
                                      Get.back();
                                    })
                              },
                          child: Text(
                            "> 註銷賬號",
                            style: textStyle,
                          )),
                    ),
                  ),
                ],
                shrinkWrap: true,
                padding: const EdgeInsets.symmetric(horizontal: 24),
              ),
              Container(
                margin: const EdgeInsets.only(top: 20),
                alignment: Alignment.center,
                child: Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: 0, vertical: 12.w),
                        alignment: Alignment.center,
                        width: 150,
                        decoration: BoxDecoration(
                            color: MyColors.green_6915761,
                            borderRadius: BorderRadius.circular(25.w)),
                        child: Text('登出',
                            style: getTextStyle(20.sp,
                                fontType: FontType.BOLD, color: Colors.white)))
                    .setOnClickListener(() {
                  Get.defaultDialog(
                      title: "確定退出當前賬號嗎？",
                      textCancel: "取消",
                      textConfirm: "確定",
                      middleText: "",
                      buttonColor: Colors.white,
                      cancelTextColor: MyColors.black_0000011,
                      confirmTextColor: MyColors.black_0000011,
                      radius: 20.w,
                      onConfirm: () {
                        SpUtil.clear();
                        //初始化極光
                        ChatHousePush.instance.initPlatformState();
                        Get.offAll(const SelectRolePage());
                        //獲取token
                        String token = SpUtil.getString(Keys.token);
                        LogUtil.d("TOKEN: $token");
                      },
                      onCancel: () {
                        Get.back();
                      });
                }),
              )
            ],
          ),
        ));
  }
}

class MyContainer extends StatelessWidget {
  const MyContainer({
    Key? key,
    required this.child,
  }) : super(key: key);

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 4, bottom: 4),
      child: child,
    );
  }
}

class MyText extends StatelessWidget {
  const MyText({
    Key? key,
    required this.textStyle, required this.str, required this.color, required this.bgColor, required this.iconData,
  }) : super(key: key);

  final TextStyle textStyle;
  final String str;
  final IconData iconData;
  final Color color;
  final Color bgColor;

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width*0.6,
      ),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.all(
          Radius.circular(10),
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          children: [
            Expanded(
              child: Text(
                str,
                style: textStyle,
              ),
            ),
            Icon(
              iconData,
              color: color,
              size: 30.0,
            ),
          ],
        ),
      ),
    );
  }
}

class MyTextNoIcon extends StatelessWidget {
  const MyTextNoIcon({
    Key? key,
    required this.textStyle, required this.str, required this.bgColor,
  }) : super(key: key);

  final TextStyle textStyle;
  final String str;
  final Color bgColor;

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        minHeight: 0, //minimum height
        minWidth: 0, // minimum width
        maxHeight: MediaQuery
            .of(context)
            .size
            .height,
        //maximum height set to 100% of vertical height
        maxWidth: MediaQuery
            .of(context)
            .size
            .width * 0.6,
        //maximum width set to 100% of width
      ),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.all(
          Radius.circular(10),
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          children: [
            Expanded(
              child: Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  str,
                  style: textStyle,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
